package com.huwei.controller;


import com.huwei.controller.valid.*;
import com.huwei.entity.UserAccount;
import com.huwei.servie.AuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/core")
public class AuthenticationController {

    @Autowired
    @Qualifier("authenticationService")
    private AuthenticationService authenticationService;

    /**
     * 密码注册
     *
     * @param userAccount
     * @param errors
     * @return
     */
    @PostMapping(value = "registerPassword", produces = {"application/json; charset=UTF-8"})
    public String registerPassword(@Validated({UsernameValid.class, PasswordValid.class}) UserAccount userAccount
            , Errors errors, HttpServletRequest request) {
        userAccount.setRegisterIpv4(request.getRemoteAddr());
        return authenticationService.registerPassword(userAccount);
    }

    @PostMapping(value = "registerCode", produces = {"application/json; charset=UTF-8"})
    public String registerCode(@Validated({PhoneValid.class}) UserAccount userAccount
            , @Validated({SmsCodeValid.class}) TempParamterEntity tpe
            , Errors errors, HttpServletRequest request) {
        userAccount.setRegisterIpv4(request.getRemoteAddr());
        return authenticationService.registerCode(userAccount, tpe.getSmsCode());
    }

    /**
     * 短信验证码登录
     *
     * @return
     */
    @PostMapping(value = "/loginCode", produces = {"application/json; charset=UTF-8"})
    public String loginCode(@Validated({PhoneValid.class}) UserAccount userAccount,
                            @Validated({SmsCodeValid.class}) TempParamterEntity tpe, Errors error, HttpServletRequest request) {
        userAccount.setLastLoginIpv4(request.getRemoteAddr());
        return authenticationService.loginCode(userAccount.getPhone(), tpe.getSmsCode());
    }

    /**
     * 密码登录
     *
     * @param username
     * @param password
     * @return
     */
    @PostMapping(value = "/loginPassword", produces = {"application/json; charset=UTF-8"})
    public String loginPassword(@Validated({UsernameValid.class, PasswordValid.class}) UserAccount userAccount, Errors errors, HttpServletRequest request) {
        userAccount.setLastLoginIpv4(request.getRemoteAddr());
        return authenticationService.loginPassword(userAccount);
    }

}
